package sgg.algorithm.datastructure.stack;

import java.util.Scanner;

/**
 * @author: Michael
 * @date: 2025/4/27
 * @desc:
 */
public class LinkedListStackDemo {

    public static void main(String[] args) {
        LinkedListStack linkedListStack = new LinkedListStack();
        String key = "";
        boolean loop = true;
        Scanner scanner = new Scanner(System.in);

        while (loop){
            System.out.println("s(show): 显示栈");
            System.out.println("e(exit): 退出程序");
            System.out.println("i(push): 添加数据到栈");
            System.out.println("h(pop): 从栈取出数据");
            System.out.println("请输入你的选择");

            key = scanner.next();
            switch (key){
                case "s":
                    linkedListStack.list();
                    break;
                case "e":
                    scanner.close();
                    loop = false;
                    break;
                case "i":
                    System.out.println("输出一个数");
                    int value = scanner.nextInt();
                    linkedListStack.push(value);
                    break;
                case "h":
                    try {
                        int res = linkedListStack.pop();
                        System.out.printf("取出的数据是%d\n", res);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                default:
                    break;
            }
        }

        System.out.println("程序退出");
    }

}


class LinkedListStack {

    Node top = null;

    public boolean isEmpty() {
        return null == top;
    }

    // 入栈操作
    public void push(int item) {
        Node newNode = new Node(item);
        newNode.next = top; // 新节点指向当前栈顶
        top = newNode;     // 更新栈顶为新节点
    }

    // 出栈操作
    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈为空，无法弹出元素");
        }
        int data = top.value;
        top = top.next; // 栈顶指向下一个节点
        return data;
    }

    // 遍历并打印栈内容（从栈顶到栈底）
    public void list() {
        Node current = top;
        System.out.print("栈内容（顶→底）: ");
        while (current != null) {
            System.out.print(current.value + " ");
            current = current.next;
        }
        System.out.println();
    }
}

class Node {
    public int value;
    public Node next;

    public Node(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }
}